/**
 * Created by xinxinran on 2018/7/17.
 */
'use strict';

class DelayThrottleController {
    static decorate(delay, decoratedFn) {
        let curThrottle = new DelayThrottleController(delay, this);
        let returnFn = function () {
            let ctx = this, args = arguments;
            curThrottle.throttleDo(() => decoratedFn.apply(ctx, args));
        };
        returnFn.clearThrottle = () => curThrottle.clearThrottle();
        return returnFn;
    }

    constructor(delayMillionSeconds, scope) {
        this.delay = delayMillionSeconds;
        this.timer = null;
        this.actionScope = scope;
    }

    throttleDo(action, payload) {
        if (this.timer) {
            clearTimeout(this.timer);
        }
        this.timer = setTimeout(() => {
            action.call(this.actionScope, payload);
        }, this.delay);
    }

    clearThrottle() {
        if (this.timer) {
            clearTimeout(this.timer);
        }
    }
}

function createDelayThrottle(delay, scope) {
    return new DelayThrottleController(delay, scope);
}

export default createDelayThrottle;
